package com.sfx.concurrent.demo.concurrent.pattern.join.GuardedTimeoutEffect;

/**
 * Description:  保护性暂停模式 + 超时效果
 */

public class GuardedObject {
    private Object response;
    //获取结果
    public Object get(long timeout){
        synchronized (this){
            long begin = System.currentTimeMillis();
            long passTime = 0;
            while(response==null){
                //应该等待的时间
                long waitTime =  timeout - passTime;
                if(waitTime<=0){
                    break;
                }
                try {
                    this.wait(waitTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                passTime = System.currentTimeMillis() - begin;
            }
            return response;
        }
    }
    //传入/产生 结果
    public void complete(Object response){
        synchronized (this) {
            this.response = response;
            this.notifyAll();
        }
    }
}